const Koa = require('koa')
const app = new Koa()
const ws = require("./middleware/ws")

module.exports = ({https, port, cors, koaBody, session, jwt, static, router, webSocket}) => {
  if(cors) {
    // 配置跨域
    const cors = require("./middleware/cors")
    cors(app)
  }
  if(koaBody) {
    //配置第三方中间件
    const koaBody = require('koa-body')
    app.use(koaBody({
      strict: false, // 设为false 支持delete等获取参数
      multipart: true, // 支持文件上传
      formidable: {
        // uploadDir: path.join(__dirname, 'public/upload/'), // 设置文件上传目录
        keepExtensions: true,    // 保持文件的后缀
        maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小
      }
    }));
  }

  if(session) {
    // 配置session
    const session = require('./middleware/session')
    session(app)
  }

  if(jwt) {
    // token权限拦截
    const koajwt = require('./middleware/jwt')
    koajwt(app)
  }

  if(static) {
    // 设置静态目录 ..可以设置多个 
    const serve = require('koa-static')
    app.use(serve(__dirname + '/public/'))
  }

  if(router) {
    // 引入模块化路由，启动路由， 后台页面总数据  
    const Router = require('@koa/router')()
    const routes = require('./router/index.js')
    Router.use('', routes)
    app.use(Router.routes()).use(Router.allowedMethods())
  }

  if(https) {
    // 配置https
    const sslify = require('koa-sslify').default
    const Https = require('https')
    const fs = require('fs')
    const options = {
      key: fs.readFileSync('./middleware/https/a.key'),
      cert: fs.readFileSync('./middleware/https/a.pem')
    }
    const server = Https.createServer(options, app.callback())

    if(webSocket) ws({server})

    app.use(sslify())  // 使用ssl

    server.listen(port, (err) => {
      if (err) {
        console.log('服务启动出错', err)
      } else {
        console.log('https-server运行在' + port + '端口')
      }
    })
  } else {
    if(webSocket) ws({port: 8080})
    app.listen(port,(err) => {
      if (err) {
        console.log('服务启动出错', err)
      } else {
        console.log('http-server运行在' + port + '端口')
      }
    });
  }
}